using System;

namespace Tycho.Parser.Peg {
    public class OperatorKeywordProduction : Production {
        private readonly string Operator;
        private readonly IProduction OperatorProduction;

        public OperatorKeywordProduction (string op) : this (op, new OperatorProduction ()) {}

        public static Terminal CreateTerminal (string op) {
            return new Terminal (new OperatorKeywordProduction (op));
        }

        public OperatorKeywordProduction (string op, IProduction operatorProduction) {
            Operator = op;
            OperatorProduction = operatorProduction;
            Name = "'" + Operator + "'";
            ErrorInformation = new KeywordErrorInformation (Operator);
        }

        protected override ParseResult ReallyParse (char[] source, int startIndex, ParseContext context, string sourceString, ParseEnvironment parseEnvironment) {
            ParseResult result = OperatorProduction.Parse (source, startIndex, context, sourceString, parseEnvironment);

            if (result != null) {
                var term = result.Term as IdentifierTerm;

                if (term != null) {
                    if (term.Name == Operator) {
                        return new ParseResult (result.Index, null, context);
                    }
                }
            }

            return null;
        }
    }
}